﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StudentInformation_Demo.Models;
using StudentInformation_Demo.Services.Interface;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace StudentInformation_Demo.Controllers
{
    public class AccountController : Controller
    {
        private readonly IUserServices services;

        public AccountController(IUserServices services)
        {
            this.services = services;
        }
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(User users)
        {
            if (ModelState.IsValid)
            {
                if (services.IsExistAndTrueUser(users))
                {
                    //一个claim 把它想做一组key-value。 new Claim(Key, Value),
                    var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,users.UserName),
                    new Claim(ClaimTypes.NameIdentifier,users.Id.ToString()),
                };
                    //ClaimsIdentity 把它想一个作身份证  
                    var indentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    //ClaimsPrincipal表示一个人，把身份证给这个人
                    var principal = new ClaimsPrincipal(indentity);
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
                    return RedirectToAction("index", "home", null);
                }
                return Json(new { code = 200, msg = "账号密码错误" });
            }
            return View();

        }

        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Register(User user)
        {
            if (ModelState.IsValid)
            {
                var model = services.GetUser(user);
                if (model == null)
                {
                    services.AddUser(user);
                    services.Save();
                    //return Ok(new { code = 200, message = "创建成功" });
                    return View("Login");
                }
                return Json(new { code = 403, message = "创建失败，这个账号已经存在" });
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login");
        }
    }
}
